﻿using System.Collections.Generic;
using System.Linq;
using Monkey.Warrenty.EntityModel;

namespace Monkey.Warrenty.Data.Interfaces
{
    public class RoleDao : IRoleDao
    {
        public List<Role> GetAll()
        {
            using (var db = new MonkeyWarrantyEntities())
            {
                return db.Roles.ToList();
            }
        }

        public void AddUsersToRole(int roleId, int[] userIds)
        {
            throw new System.NotImplementedException();
        }

        public void RemoveUsersFromRole(int roleId, int[] userIds)
        {
            throw new System.NotImplementedException();
        }

        public List<Role> GetRoleOfUser(int userId)
        {
            throw new System.NotImplementedException();
        }

        public List<Employee> GeGetEmployeesOfRole(int roleId)
        {
            using (var db = new MonkeyWarrantyEntities())
            {
                return (from e in db.Employees
                        join er in db.Employees_Roles
                        on e.Id equals er.EmployeeId
                        where er.RoleId == roleId
                        select e).ToList();
            }
        }

        public Role GetById(int roleId)
        {
            using (var db = new MonkeyWarrantyEntities())
            {
                return db.Roles.FirstOrDefault(x => x.Id == roleId);
            }
        }

        public void AssignToRole(int roleId, List<int> assignedIds)
        {
            using (var db = new MonkeyWarrantyEntities())
            {
                // delet existing
                var existingEmployees = db.Employees_Roles.Where(x => x.RoleId == roleId);

                foreach (var existingEmployee in existingEmployees)
                {
                    db.Employees_Roles.DeleteObject(existingEmployee);
                }
                db.SaveChanges();

                // insert new
                foreach (var assignedId in assignedIds)
                {
                    db.Employees_Roles.AddObject(new Employees_Roles
                    {
                        RoleId = roleId,
                        EmployeeId = assignedId
                    });
                }
                db.SaveChanges();
            }
        }

        public List<Role> GetRolesOfEmployee(int employeeId)
        {
            using (var db = new MonkeyWarrantyEntities())
            {
                return (from r in db.Roles
                        join er in db.Employees_Roles
                        on r.Id equals er.RoleId
                        where er.EmployeeId == employeeId
                        select r).ToList();
            }
        }
    }
}
